package com.example.taobaounion3.ui.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.example.taobaounion3.R;

//功能自动轮播
public class AutoLoopViewPager extends ViewPager {
    //切换间隔时长
    public static final int DEFAULT_DURATION=3000;

    private int mDuration=DEFAULT_DURATION;

    public AutoLoopViewPager(@NonNull Context context) {
        this(context,null);
    }

    public AutoLoopViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        //读取属性
        init(context,attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray t=context.obtainStyledAttributes(attrs, R.styleable.AutoLoopStyle);
        //获取属性
        mDuration=t.getInteger(R.styleable.AutoLoopStyle_duration,DEFAULT_DURATION);
        //回收
        t.recycle();
    }

    private boolean isLoop=false;

    private Runnable mTask=new Runnable() {
        @Override
        public void run() {
            int currentItem=getCurrentItem();
            currentItem++;
            setCurrentItem(currentItem);
            if (isLoop) {
                postDelayed(this,mDuration);
            }
        }
    };

    /**
     * 设置时间时长，单位：毫秒.
     *
     * @param duration the duration
     */
    public void setDuration(int duration){
        this.mDuration=duration;
    }

    public void startLoop(){
        isLoop=true;
        //先拿到当前的位置
        post(mTask);

    }

    public void stopLoop(){
        isLoop=false;
        removeCallbacks(mTask);
    }

}
